package com.bestcem.xm.survey.service.reportHandler.type;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.service.reportHandler.BaseReportHandler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class SingleScoreHandler implements BaseReportHandler {

    @Override
    public Double getMaxScore(JSONObject question, JSONArray scoreRule) {
        if (question == null || question.getJSONArray("items") == null) {
            return 0d;
        }
        JSONArray items = question.getJSONArray("items");
        JSONObject scoreGidDict = getScoreGidDict(scoreRule);
        List<Double> scoreList = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            String oGid = item.getString("gid");
            Double score = scoreGidDict.getDouble(oGid);
            score = score == null ? 0d : score;
            scoreList.add(score);
        }

        return convertFloat(Collections.max(scoreList));
    }

    @Override
    public Double getScore(JSONObject question, Object answers, JSONArray scoreRule, JSONObject scoreConfig) {
        if (answers != null) {
            String oGid = ((JSONArray)answers).getString(0);
            JSONObject scoreGidDict = getScoreGidDict(scoreRule);
            return convertFloat(scoreGidDict.getDouble(oGid));
        }
        return 0d;
    }

    @Override
    public List<String> getQuestionTypeValue() {
        return Arrays.asList("single", "image_select");
    }
}
